import os
import json
from datetime import datetime
from utils.file_utils import get_detection_data_path, get_rootheal_data_path


class FileService:
    @staticmethod
    def save_detection_data(data, filename=None):
        """保存检测数据到detection_data目录"""
        try:
            # 生成文件名
            if not filename:
                timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                filename = f"detection_{timestamp}.json"
            
            # 获取保存路径
            detection_data_path = get_detection_data_path()
            file_path = os.path.join(detection_data_path, filename)
            
            # 确保目录存在
            os.makedirs(detection_data_path, exist_ok=True)
            
            # 保存数据到文件
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
            
            return {
                'success': True,
                'filename': filename,
                'url': f'/detection-data/{filename}'
            }
        except Exception as e:
            return {'success': False, 'error': f'Failed to save data: {str(e)}'}
    
    @staticmethod
    def save_rootheal_data(data, filename=None):
        """保存rootheal数据到rootheal_data目录"""
        try:
            # 生成文件名
            if not filename:
                timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                filename = f"rootheal_{timestamp}.json"
            
            # 获取保存路径
            rootheal_data_path = get_rootheal_data_path()
            file_path = os.path.join(rootheal_data_path, filename)
            
            # 确保目录存在
            os.makedirs(rootheal_data_path, exist_ok=True)
            
            # 保存数据到文件
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
            
            return {
                'success': True,
                'filename': filename,
                'url': f'/rootheal-data/{filename}'
            }
        except Exception as e:
            return {'success': False, 'error': f'Failed to save data: {str(e)}'}